const { promisify } = require('util')
const { program } = require('commander')
const execCommand = require('../utils/execCommand')
const compileEjs = require('../utils/compileEjs')
const writeFile = require('../utils/writeFile')
const download = promisify(require('download-git-repo'))

async function createProject(project) {
  try {
    // direct默认找master，如果github上主分支是main 需手动修改
    const VUE_REPO = 'direct:https://gitee.com/qt-cli/vue3-template.git#master'
    // 1.编写所需要操作的代码
    await download(VUE_REPO, project, { clone: true })
    // 2.增加下载好的提升
    // console.log(`cd ${project}`)
    // console.log('npm install / pnpm install')
    // console.log(`npm run dev / pnpm run dev`)

    // 判断不同平台执行的命令
    const commandPlatform = process.platform === 'win32' ? 'npm.cmd' : 'npm'
    // 3.帮助用户执行npm install, cwd参数：执行的模板文件夹
    await execCommand(commandPlatform, ['install'], {cwd: `./${project}`})
    // 4.帮助用户执行npm run dev
    await execCommand(commandPlatform, ['run', 'serve'], {cwd: `./${project}`})
  } catch(err) {
    console.log('github连接失败，请稍后重试~')
  } 
}

async function addComponent(cpnname) {
  // 提取创建好模板 component.vue.ejs
  // 编译模板文件
  const result = await compileEjs('component.vue.ejs', { name: cpnname, lowername: cpnname.toLowerCase() })
  // console.log(result)
  // 将文件写入对应目录下
  const dest = program.opts().dest || 'src/components'
  await writeFile(`${dest}/${cpnname}.vue`, result)
}

module.exports = { createProject, addComponent }